home *** CD-ROM | disk | FTP | other *** search
- Path: mail2news.demon.co.uk!genesis.demon.co.uk
- From: Lawrence Kirby <fred@genesis.demon.co.uk>
- Newsgroups: comp.lang.c
- Subject: Re: Need help with QSORT
- Date: Sat, 06 Jan 96 13:54:37 GMT
- Organization: none
- Message-ID: <820936477snz@genesis.demon.co.uk>
- References: <4ckjfi$oat@swifty.cfa.org> <4cl0rb$2id@news.iag.net>
- Reply-To: fred@genesis.demon.co.uk
- X-NNTP-Posting-Host: genesis.demon.co.uk
- X-Newsreader: Demon Internet Simple News v1.27
- X-Mail2News-Path: genesis.demon.co.uk
-
- In article <4cl0rb$2id@news.iag.net> jatmon@iag.net "John R Buchan" writes:
-
- ...
-
- >int sort_function( const void *c, const void *d)
- > {
- > float f;
- > const struct site_specs *a = c, *b = d; /* jatmon added const */
- >
- >/* a =(struct site_specs *) c; the casts are unnecessary with const */
- >/* b =(struct site_specs *)d; */
- >
- >/*
- > if((a->XC == b->XC) && (a->YC == b->YC) && (a->ZC == b->ZC))
- > return(0);
- >
- > if(a->ZC < b->ZC)
- > return(-1);
- > if(a->ZC > b->ZC)
- > return(1);
- >
- > if(a->YC < b->YC)
- > return(-1);
- > if(a->YC > b->YC)
- > return(1);
- >
- > if(a->XC < b->XC)
- > return(-1);
- > if(a->XC > b->XC)
- > return(1);
- >
- >The return values don't have to be -1, 0, 1. Just negative, 0, positive.
- >
-
- >Comparing floats is a bit tricky.
-
- It can be if you're testing for equality in some sense. As far as sorting
- goes all you really need is a well-defined ordering and float comparison
- should be fine for that. However comparison isn't the only thing that is
- 'tricky' about floating point.
-
- The c.l.c faq (Frequently Asked Question)
- >list explains the problems involved. The list is available for anonymous ftp
- >from rtfm.mit.edu /pub/usenet/comp.lang.c.
- >*/
- > f = a->ZC - b->ZC;
-
- This may overflow. There is also the issue whether it will produce the
- same ordering results (where equality is concerned) as a->ZC (>,=,<) b->ZC.
- If not this may prove inconsistent with other parts of the code and
- cause problems.
-
- > if( f == 0)
- > {
- > f = a->YC - b->YC;
- > if( f == 0)
- > {
- > f = a->XC - b->XC;
- > }
- > }
- >
- > return f;
-
- Converting a float to int could very easily overflow or truncate to zero so
- you do need to do something like return -1, 0, 1 explicitly.
-
- I suggest something like the following:
-
- int sort_function( const void *c, const void *d)
- {
- const struct site_specs *a = c, *b = d;
-
- if (a->ZC != b->ZC)
- return (a->ZC > b->ZC) ? 1 : -1;
-
- if (a->YC != b->YC)
- return (a->YC > b->YC) ? 1 : -1;
-
- if (a->XC != b->XC)
- return (a->XC > b->XC) ? 1 : -1;
-
- return 0;
- }
-
- --
- -----------------------------------------
- Lawrence Kirby | fred@genesis.demon.co.uk
- Wilts, England | 70734.126@compuserve.com
- -----------------------------------------
-